package com.mjgy.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.utils.StringUtils;
import com.common.utils.R;
import com.mjgy.entity.MUserEntity;
import com.mjgy.entity.MessageEntity;
import com.mjgy.entity.UserWithdrawEntity;
import com.mjgy.repository.MUserRepository;
import com.mjgy.repository.UserWithdrawRepository;
import com.mjgy.service.UserWithdrawService;

/**
* @Description: TODO
* @author quanlq
* @date 2018年10月1日
* @version V1.0
*/
@Service
@Transactional
public class UserWithdrawServiceImpl implements UserWithdrawService {
	
	@Autowired
	private UserWithdrawRepository userWithdrawRepository;
	@Autowired
	private MUserRepository mUserRepository;
	@Autowired
	private EntityManager em;
	
	@Override
	public void save(UserWithdrawEntity userWithdrawEntity) {
		MUserEntity user = em.find(MUserEntity.class, userWithdrawEntity.getUserId());
		if(user != null) {
			user.setWallet(user.getWallet().subtract(userWithdrawEntity.getAmount()));
			BigDecimal frozenWallet = user.getFrozenWallet();
			if(frozenWallet == null){
				frozenWallet = BigDecimal.ZERO;
			}
			user.setFrozenWallet(frozenWallet.add(userWithdrawEntity.getAmount()));
			em.merge(user);
		}
		
		userWithdrawRepository.save(userWithdrawEntity);
	}

	@Override
	public List<Map<String, Object>> findListByStatus(Integer status, Long id, String city, String nickname, 
			String startTime, String endTime, Integer page, Integer size) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		sql.append("usr.id");
		sql.append(",uw.id userWithdrawId");
		sql.append(",usr.sex");
		sql.append(",usr.province");
		sql.append(",usr.city");
		sql.append(",usr.nickname");
		sql.append(",usr.identity");
		sql.append(",uw.apply_time");
		sql.append(",uw.amount");
		sql.append(",uw.actual");
		sql.append(",uw.account");
		sql.append(",uw.name");
		sql.append(",uw.status");
		sql.append(" FROM e_user_withdraw uw");
		sql.append(" LEFT JOIN e_user usr ON uw.user_id = usr.id");
		sql.append(" WHERE 1 = 1");
		if(id != null){
			sql.append(" AND usr.id = :id");
		}
		if(StringUtils.isNotEmpty(city)){
			sql.append(" AND usr.city LIKE CONCAT('%', CONCAT(:city, '%'))");
		}
		if(StringUtils.isNotEmpty(nickname)){
			sql.append(" AND usr.nickname LIKE CONCAT('%', CONCAT(:nickname, '%'))");
		}
		if(StringUtils.isNotEmpty(startTime)){
			sql.append(" AND LEFT(uw.apply_time, 10) >= :startTime");
		}
		if(StringUtils.isNotEmpty(endTime)){
			sql.append(" AND LEFT(uw.apply_time, 10) <= :endTime");
		}
		if(status != null){
			if(status == 0){
				sql.append(" AND uw.status = :status");
			}else{
				sql.append(" AND uw.status != 0");
			}
		}
		sql.append(" ORDER BY uw.apply_time DESC");			
		sql.append(" LIMIT :pageIndex, :size");
		
		Query query = em.createNativeQuery(sql.toString());
		if(id != null){
			query.setParameter("id", id);
		}
		if(StringUtils.isNotEmpty(city)){
			query.setParameter("city", city);
		}
		if(StringUtils.isNotEmpty(nickname)){
			query.setParameter("nickname", nickname);
		}
		if(StringUtils.isNotEmpty(startTime)){
			query.setParameter("startTime", startTime);
		}
		if(StringUtils.isNotEmpty(endTime)){
			query.setParameter("endTime", endTime);
		}
		if(status != null && status == 0){
			query.setParameter("status", status);
		}
		query.setParameter("pageIndex", (page-1)*size);
		query.setParameter("size", size);
		List resultList = query.getResultList();
		
		List<Map<String, Object>> list = new ArrayList<>();
		for(Object row : resultList){
			Object[] cells = (Object[]) row;
			Map<String, Object> map = new HashMap<>();
			map.put("id", cells[0]);
			map.put("userWithdrawId", cells[1]);
			map.put("sex", cells[2]);
			map.put("province", cells[3]);
			map.put("city", cells[4]);
			map.put("nickname", cells[5]);
			map.put("identity", cells[6]);
			map.put("applyTime", cells[7]);
			map.put("amount", cells[8]);
			map.put("actual", cells[9]);
			map.put("account", cells[10]);
			map.put("name", cells[11]);
			map.put("status", cells[12]);
			list.add(map);
		}
		
		return list;
	}

	@Override
	public R dealUserWithdraw(Long id, Integer status) {
		UserWithdrawEntity userWithdrawEntity = userWithdrawRepository.findOne(id);
		if(userWithdrawEntity == null){
			return R.error(202, "用户提现实体不能为空");
		}
		MUserEntity mUserEntity = mUserRepository.findOne(userWithdrawEntity.getUserId());
		if(mUserEntity == null){
			return R.error(202, "用户不存在");
		}
		
		MessageEntity messageEntity = new MessageEntity();
		messageEntity.setUserId(userWithdrawEntity.getUserId());
		messageEntity.setIsChecked(0);
		messageEntity.setType("1");
		messageEntity.setSendTime(new Date());
		
		BigDecimal frozenWallet = mUserEntity.getFrozenWallet();
		if(frozenWallet == null){
			frozenWallet = BigDecimal.ZERO;
		}
		if(status == 1){	//已执行
			mUserEntity.setFrozenWallet(frozenWallet.subtract(userWithdrawEntity.getAmount()));
			em.merge(mUserEntity);
			messageEntity.setContent("您申请提现的" + userWithdrawEntity.getAmount() + "元已执行，实际到账" + 
			userWithdrawEntity.getActual() + "元，详情请联系客服");
			em.persist(messageEntity);
		}
		if(status == 2){	//已打回
			mUserEntity.setFrozenWallet(frozenWallet.subtract(userWithdrawEntity.getAmount()));
			mUserEntity.setWallet(mUserEntity.getWallet().add(userWithdrawEntity.getAmount()));
			em.merge(mUserEntity);
			messageEntity.setContent("您申请提现的" + userWithdrawEntity.getAmount() + "元已被打回，详情请联系客服");
			em.persist(messageEntity);
		}
		userWithdrawEntity.setStatus(status);
		em.merge(userWithdrawEntity);
		
		return R.success();
	}

}
